﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json.Serialization;

namespace Xejen.Communication.Socket
{
    /// <summary>
    /// 表示Socket请求结果
    /// <para>
    /// 使用<see langword="byte[]"/>类型作为返回的数据结果类型，是为了适用所有数据类型，这样可以做到最通用的效果
    /// </para>
    /// </summary>
    /// <typeparam name="T">返回值的类型</typeparam>
    /// <creator>marc</creator>
    public class SocketResponse<T> : Result<T>
    {
        /// <summary>
        /// 字符编码：默认UTF-8
        /// </summary>
        [JsonIgnore]
        public Encoding Encoding { get; private set; } = Encoding.UTF8;

        /// <inheritdoc cref="SocketResponse{T}"/>
        public SocketResponse()
        {

        }

        /// <inheritdoc cref="SocketResponse{T}"/>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        public SocketResponse(Encoding encoding = default) : base()
        {
            SetEncoding(encoding);
        }

        /// <summary>
        /// 返回一个表示成功的<see cref="SocketResponse{T}"/>对象
        /// </summary>
        /// <param name="returnData"><inheritdoc cref="Result{T}.ReturnData" path="/summary"/></param>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        public static SocketResponse<T> Success(T returnData, Encoding encoding = default)
        {
            SocketResponse<T> response = new SocketResponse<T>(encoding);
            response.ReturnData = returnData;
            response.Code = SuccessCode;

            return response;
        }

        /// <summary>
        /// 返回一个表示失败的<see cref="SocketResponse{T}"/>对象
        /// </summary>
        /// <param name="code"><inheritdoc cref="IResult.Code" path="/summary"/></param>
        /// <param name="exception"><inheritdoc cref="IResult.Exception" path="/summary"/></param>
        public static SocketResponse<T> Fail(int code, Exception exception = default)
        {
            return new SocketResponse<T>()
            {
                Code = code,
                Exception = exception,
            };
        }

        /// <summary>
        /// 设置编码
        /// </summary>
        /// <param name="encoding"><inheritdoc cref="Encoding" path="/summary"/></param>
        private void SetEncoding(Encoding encoding)
        {
            if (encoding == null)
            {
                return;
            }

            Encoding = encoding;
        }
    }
}
